package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/jsonx"
	"mall_srv/models/cache"
	"mall_srv/models/mysql"
	"time"

	"mall_srv/internal/svc"
	"mall_srv/mall"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 列表展示
func (l *ShopListLogic) ShopList(in *mall.ShopListRequest) (*mall.ShopListResponse, error) {
	// todo: add your logic here and delete this line

	var shops []mysql.Shop
	mysql.DB.Debug().Find(&shops)

	key := fmt.Sprintf("shop_list_")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		jsonx.Unmarshal([]byte(result), &shops)
	} else {
		marshal, _ := json.Marshal(shops)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*5)
	}

	var shopList []*mall.ShopList
	for _, shop := range shops {
		list := mall.ShopList{
			Name:  shop.Name,
			Price: float32(shop.Price),
			Img:   shop.Img,
			Stock: int64(shop.Stock),
		}
		shopList = append(shopList, &list)
	}

	return &mall.ShopListResponse{}, nil
}
